from fastapi import APIRouter, Query, Path, Body,Request, Header
from sqlalchemy.orm import Session
from db import Db
from utils import UserAgent
from models import ResponseModel,ResponseList
from core.token_service import TokenService
from schemas.user_schema import UserCreate,userschema,UserInfo
from curd.user import GetUserList,register_user,del_user,update_user,authenticate_user
from utils.log_utils import logger
from datetime import datetime

# 创建一个 APIRouter 实例
user_router = APIRouter(
	prefix='/user',
	tags=['user 账户信息']
)

@user_router.post('/register-user',summary="注册账户")
def Register(
		d:Session = Db,
		user: UserCreate = Body(..., description="用户信息")
):
	user = register_user(db=d, user=user)
	return  user

@user_router.post('/login', summary="用户登录", description="用户登录，没有账户就注册")
async def login_redis(
		request: Request,
		d:Session = Db,
		username: str = Body(...,title="用户名", description="数据库用户名"),
		password: str =Body(...,title="密码", description="数据库密码")
):
	# 验证用户凭证（伪代码）
	user = authenticate_user(db=d, username=username, password=password)
	machine_info = UserAgent( request)
	
	# 创建令牌对
	access_token, refresh_token = TokenService.create_tokens(
		user_id=str(user.id),
		payload={
			"device": machine_info['device_info'],
			"ip": machine_info['ip_address'],
			# "device_type": machine_info['device_info.device_type'],
		}
	)
	# print(type(access_token), access_token)
	# print(type(f'user:token:{user.id}'), f'user:token:{user.id}')
	# 设置redis缓存 8小时过期
	await request.app.state.redis.set(f'user:token:{user.id}',str(access_token),ex=8*60*60)
	logger.info('登录成功')
	# 可以记录登录信息
	return {
		"access_token": access_token,
		"refresh_token": refresh_token,
		"token_type": "bearer"
	}
	


@user_router.post('/logout',summary="用户登出", description="用户登出")
async def expire_redis(request: Request, authorization: str = Header(None)):
	token = authorization.split(" ", 1)[1]
	try:
		payload = TokenService.verify_token(token)
		user_id = payload.get("sub")
		if not user_id:
			return {"message": "token无效，未找到用户ID"}
		redis_key = f'user:token:{user_id}'
		await request.app.state.redis.delete(redis_key)
		return {"message": "登出成功"}
	except Exception as e:
		return {"message": f"登出失败: {str(e)}"}


@user_router.delete('/del-account{id}',summary="删除用户", description="软删除账户")
def DeleteUser(
    db: Session = Db,
    id: str = Path(..., description="用户ID")
):
    return del_user(db=db, id=id)

@user_router.post('/update-account',summary="更新用户", description="更新账户信息")
def UpdateUser(
    db: Session = Db,
    user: UserInfo = Body(..., description="用户信息"),
    authorization: str = Header(..., description="认证token")
):
    # 从token获取用户id
    token = authorization.split(" ", 1)[1]
    payload = TokenService.verify_token(token)
    user_id = payload.get("sub")
    if not user_id:
        return {"message": "token无效，未找到用户ID"}
    # 设置 update_by 和 updated_time
    user.update_by = user_id
    user.updated_time = datetime.now()
    d = update_user(db=db, el=user)
    # 过滤敏感字段
    data = d.get("data")
    if hasattr(data, "__dict__"):
        user_dict = data.__dict__
        user_dict.pop("password", None)
        user_dict.pop("salt", None)
        user_dict.pop("_sa_instance_state", None)
        d["data"] = user_dict
    return d

@user_router.post('/user-list',summary="用户数据", description="获取用户列表")
def UserList(
		db: Session = Db,
		d: userschema=Body(..., description="用户信息")
):
	res = GetUserList(db= db, dto=d)
	# 过滤每个用户对象中的password和salt字段
	if isinstance(res.get("data"), list):
		for user in res["data"]:
			if hasattr(user, "__dict__"):
				user_dict = user.__dict__
				user_dict.pop("password", None)
				user_dict.pop("salt", None)
				user_dict.pop("_sa_instance_state", None)  # SQLAlchemy对象的内部属性
				# 替换为字典
				res["data"][res["data"].index(user)] = user_dict
	return  res

